package com.example.qqfake;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class IPActivity extends AppCompatActivity {
    private String peerAddress; // 假设这是节点B的IP地址
    private final int port = 12345;// 通信使用的端口
    public Socket socket;
    public PrintWriter out;
    public BufferedReader in;
    public ServerSocket serverSocket;
    public Socket clientSocket;
    private RecyclerView rv;

    private TextView your_name;
    private String goal_name;
    private EditText content;
    private User user;
    private List<Chat_content> list = new ArrayList<>();
    public MyAdapter adapter = new MyAdapter(list);
    private Button send;
    private ImageView exit_chat;
    public int i=0;//记录聊天条数
    private String myid;
    private String goal_id;
    private String type;
    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;
    // 生成密钥
    private SecretKey key;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_ipactivity);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //数据从数据库中获得，同时还要获取对话对象的唯一id
        // 获取SharedPreferences实例，文件名为"myPreferences"，与MainActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
        // 读取数据，键为"User_id"
        myid = sharedPreferences.getString("User_id","hhh");
        int myidid = Integer.parseInt(myid);
        user=new User(myidid);

        try {
            key = generateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        Intent intent = getIntent();
        goal_name = intent.getStringExtra("chat_name");
        goal_id = intent.getStringExtra("chat_partner");
        if(intent.hasExtra("IP")){
            peerAddress = intent.getStringExtra("IP");
            Log.v("msg","ip_chatting");
            //开启客户端
            type = "1";


        }else{
            Log.v("msg","ip_chatting0");
            //开启服务器端
            type  = "0";

            new Thread(() -> {
                try {

                    serverSocket = new ServerSocket(port);
                    //等待接收socket
                    clientSocket = serverSocket.accept();
                    // 初始化输入输出流
                    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    out = new PrintWriter(clientSocket.getOutputStream(), true);

                    new Thread(this::readMessages).start();



                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

        }



        //绑定控件
        content = findViewById(R.id.content1);
        send = findViewById(R.id.send1);
        your_name = findViewById(R.id.your_name1);
        your_name.setText(goal_name);
        exit_chat = findViewById(R.id.exit_chat1);


        rv = findViewById(R.id.rv1);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

        rv.setLayoutManager(linearLayoutManager);


        adapter = new MyAdapter(list);
        rv.setAdapter(adapter);


        exit_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(IPActivity.this, MainActivity.class);
                startActivity(intent);
                IPActivity.this.finish();

            }
        });

        //发送消息
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(type.equals("1")){
                    //子线程开启socket
                    new Thread() {

                        private BufferedReader bufferedReader = null;
                        public void run() {
                            //发送socket
                            try {

                                socket= new Socket(peerAddress, port);

                                String content1 = null;
                                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                                //子线程发送消息
                                String message = content.getText().toString();


                                // 加密数据
                                //String encryptedData = encrypt(message, key);
                                //out.println(encryptedData);
                                out.println(message);


                                runOnUiThread(new Runnable() {//此run方法将由主线程运行
                                    @Override
                                    public void run() {
                                        //此处图片需要读取数据库中的头像
                                        Chat_content p1 = new Chat_content(1,content.getText().toString(),R.drawable.right);
                                        // 通知适配器新元素添加
                                        adapter.addItem(p1);
                                        i++;
                                        content.setText("");

                                    }
                                });
                                while((content1 = bufferedReader .readLine()) != null) {
                                    String finalContent = content1;
                                    runOnUiThread(new Runnable() {//此run方法将由主线程运行
                                        @Override
                                        public void run() {
                                            //此处图片为对话对象的头像
                                            Chat_content p1 = new Chat_content(Chat_content.TYPE_ONE, finalContent,R.drawable.left);
                                            // 通知适配器新元素添加
                                            adapter.addItem(p1);
                                            i++;
                                            Log.v("msg","receiver");

                                        }
                                    });


                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            } finally{
                                try {
                                    if(bufferedReader!=null){
                                        bufferedReader.close();
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();

                }else{
                    Log.v("msg","server_send");
                    //子线程发送消息
                    String message = content.getText().toString();
                    Thread thread = new Thread(new Worker(message,out));
                    thread.start();

                    //此处图片需要读取数据库中的头像
                    Chat_content p1 = new Chat_content(1,content.getText().toString(),R.drawable.right);
                    // 通知适配器新元素添加
                    adapter.addItem(p1);
                    i++;
                    content.setText("");
                }

            }
        });


    }


    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private List<Chat_content> items;

        public MyAdapter(List<Chat_content> items) {
            this.items = items;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //1是自己发的（right），0是对面发的（left）

            View view;
            if (viewType == Chat_content.TYPE_TWO) {
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview_right, parent, false);
                return new Recycler_item_right(view);
            }
            else if(viewType == Chat_content.TYPE_ONE){

                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview_left, parent, false);
                return new Recycler_item_left(view);
            }
            else{
                return null;
            }

        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            Chat_content item = items.get(position);
            if (item.getType() == 1) {
                ((Recycler_item_right) holder).bindData(item);
            } else {
                ((Recycler_item_left) holder).bindData(item);
            }

        }
        // 提供一个方法来增加数据
        public void addItem(Chat_content item){
            items.add(item);
            notifyItemInserted(items.size() - 1);

        }

        @Override
        public int getItemCount() {
            return items.size();
        }

        @Override
        public int getItemViewType(int position) {
            return items.get(position).getType();
        }


    }

    //A端 B端公用的发送线程，需要传递发送消息，和发送的PrintWriter
    public class Worker implements Runnable {
        private String message;
        private PrintWriter out;
        public Worker(String message,PrintWriter out) {
            this.message = message;
            this.out = out;
        }
        @Override
        public void run() {
            // 使用传递的消息
            out.println(message);
        }
    }


    private void readMessages() {
        try {
            String message;
            while ((message = in.readLine()) != null) {
                Log.v("msg","receiver1");
                if(!isFinishing()){

                    // 解密数据
                    //String decryptedData = decrypt(message, key);
                    Log.v("msg","receiver2");
                    String finalMessage = message;
                    runOnUiThread(new Runnable() {//此run方法将由主线程运行

                        @Override
                        public void run() {
                            Log.v("msg","receiver3");

                            //此处图片为对话对象的头像，也是从数据库中拿
                            Chat_content p1 = new Chat_content(Chat_content.TYPE_ONE, finalMessage,R.drawable.left);
                            // 通知适配器新元素添加
                            adapter.addItem(p1);
                            i++;
                            Log.v("msg","receiver");

                        }
                    });
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    @Override
    public void onDestroy() {

        super.onDestroy();
        try{
            //关闭输入流，socket连接
            if(socket!=null){
                in.close();
                out.close();
                socket.close();
            }

        }catch(IOException e){
            e.printStackTrace();

        }

    }
    private static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE, new SecureRandom());
        return keyGenerator.generateKey();
    }

    private static String encrypt(String data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    private static String decrypt(String encryptedData, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData);
    }

}


